package com.dxx.cloud.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxx.cloud.admin.enums.ErrorEnum;
import com.dxx.cloud.admin.mapper.GoodsMapper;
import com.dxx.cloud.admin.module.entity.GoodsEntity;
import com.dxx.cloud.admin.module.request.GoodsAddRequest;
import com.dxx.cloud.admin.module.request.GoodsListRequest;
import com.dxx.cloud.admin.module.request.GoodsPageListRequest;
import com.dxx.cloud.admin.module.response.GoodsResponse;
import com.dxx.cloud.admin.module.response.GoodsSizeResponse;
import com.dxx.cloud.admin.service.IGoodsService;
import com.dxx.cloud.admin.service.IGoodsSizeService;
import com.dxx.cloud.admin.utils.EntityUtils;
import jakarta.annotation.Resource;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author dh
 * @since 2025-06-06
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsEntity> implements IGoodsService {
    @Resource
    private IGoodsSizeService goodsSizeService;


    @Override
    public List<GoodsResponse> goodsList(GoodsListRequest request) {
        if (null == request.getLevel() && null == request.getParentId()) {
            // 默认查询一级分类
            request.setLevel(0);
        }
        List<GoodsEntity> list  = list(listQueryWrapper(request));
        List<GoodsResponse> responseList = new ArrayList<>();
        for (GoodsEntity goodsEntity : list) {
            GoodsResponse response = new GoodsResponse();
            BeanUtils.copyProperties(goodsEntity, response);
            if (null != goodsEntity.getLevel()) {
                if (goodsEntity.getLevel()==0) {
                    response.setChildren(listChildren(goodsEntity.getId()));
                }else {
                    List<GoodsSizeResponse> goodsSizeResponses = goodsSizeService.goodsSizeResponseList(response.getId());
                    response.setSizeResponseList(goodsSizeResponses);
                }
            }
            if(ObjectUtils.isEmpty(response.getOrderNo())){
                response.setOrderNo(0);
            }
            responseList.add(response);
        }
        responseList.sort(Comparator.comparing(GoodsResponse::getOrderNo));
        return responseList;
    }

    private  List<GoodsResponse> listChildren(Long id){
        final List<GoodsEntity> list = list(new LambdaUpdateWrapper<GoodsEntity>().eq(GoodsEntity::getParentId, id));
        List<GoodsResponse> goodsResponses = EntityUtils.entityList2ResponseList(GoodsResponse.class, list);
        for (GoodsResponse goodsResponse : goodsResponses) {
            goodsResponse.setSizeResponseList(goodsSizeService.goodsSizeResponseList(goodsResponse.getId()));
        }
        return goodsResponses;
    }

    private static LambdaQueryWrapper<GoodsEntity> listQueryWrapper(GoodsEntity request) {
        return new LambdaQueryWrapper<GoodsEntity>()
                .eq(null != request.getId(), GoodsEntity::getId, request.getId())
                .eq(null != request.getMerId(), GoodsEntity::getMerId, request.getMerId())
                .eq(null != request.getShopId(), GoodsEntity::getShopId, request.getShopId())
                .eq(null != request.getTypeId(), GoodsEntity::getTypeId, request.getTypeId())
                .eq(null != request.getParentId(), GoodsEntity::getParentId, request.getParentId())
                .eq(null != request.getLevel(), GoodsEntity::getLevel, request.getLevel())

                .like(StringUtils.hasText(request.getName()), GoodsEntity::getName, request.getName());
    }

    @Override
    public TableDataInfo<GoodsResponse> pageList(GoodsPageListRequest request) {
        LambdaQueryWrapper<GoodsEntity> queryWrapper = listQueryWrapper(request);
        Page<GoodsEntity> page = page(new Page<>(request.getPageNum(), request.getPageSize()), queryWrapper);
        Page<GoodsResponse> goodsResponsePage = EntityUtils.page2PageResponse(GoodsResponse.class, page);
        return TableDataInfo.build(goodsResponsePage);
    }

    @Override
    public List<GoodsEntity> listByName(String name) {
        return list(new LambdaQueryWrapper<GoodsEntity>().eq(GoodsEntity::getName, name));
    }

    @Override
    public Long addGoods(GoodsAddRequest request) {
        EntityUtils.setCreator(request,request.getOperator());
        //添加商品
        //先判断商品名是否存在
        List<GoodsEntity> goodsEntityList = listByName(request.getName());
        if(!CollectionUtils.isEmpty(goodsEntityList)){
            throw new ServiceException(ErrorEnum.GOODS_ALREADY_EXIST.getMessage());
        }
        if (null != request.getParentId()) {
            GoodsEntity parentEntity = getById(request.getParentId());
            if (null != parentEntity) {
                int level = ObjectUtils.defaultIfNull(parentEntity.getLevel(),0) ;
                request.setLevel(level+1);
            }
        }
        GoodsEntity entity = EntityUtils.entity2Response(GoodsEntity.class,request);
        save(entity);
        return entity.getId();
    }

    @Override
    public GoodsResponse detailResponseById(Serializable id) {
        GoodsEntity entity = getById(id);
        GoodsResponse goodsResponse = EntityUtils.entity2Response(GoodsResponse.class, entity);
        if(null != entity) {
            goodsResponse.setSizeResponseList(goodsSizeService.goodsSizeResponseList(entity.getId()));
        }
        return goodsResponse;
    }
}
